<template>
  <div>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="姓名" prop="leaveName">
        <el-input v-model="ruleForm.leaveName" />
      </el-form-item>
      <el-form-item label="部门" prop="departmentId">
        <el-select
          v-model="ruleForm.departmentId"
          placeholder="请选择部门"
          style="width: 150px"
        >
          <el-option label="IT信息部" :value="1" />
          <el-option label="财务部" :value="2" />
          <el-option label="行政部" :value="3" />
          <el-option label="人力资源部" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="请假类别" prop="leaveType">
        <el-radio-group v-model="ruleForm.leaveType">
          <el-radio value="事假" name="type"> 事假 </el-radio>
          <el-radio value="病假" name="type"> 病假 </el-radio>
          <el-radio value="婚假" name="type"> 婚假 </el-radio>
          <el-radio value="产假" name="type"> 产假 </el-radio>
          <el-radio value="补休" name="type"> 补休 </el-radio>
          <el-radio value="工伤" name="type"> 工伤 </el-radio>
          <el-radio value="其它" name="type"> 其它 </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="请假时间" required>
        <el-col :span="11" style="margin-bottom: 15px">
          <el-form-item prop="startTime">
            <el-date-picker
              v-model="ruleForm.startTime"
              aria-label="请选择开始时间"
              type="datetime"
              placeholder="请选择开始时间"
              format="YYYY年MM月DD日 HH时"
              style="width: 100%"
              @change="handleStartTimeChange"
            />
          </el-form-item>
        </el-col>
        <el-col class="text-center" :span="2" style="margin-bottom: 15px">
          <span class="text-gray-500">&emsp;至</span>
        </el-col>
        <el-col :span="11" style="margin-bottom: 15px">
          <el-form-item prop="endTime">
            <el-date-picker
              v-model="ruleForm.endTime"
              aria-label="请选择开始时间"
              type="datetime"
              placeholder="请选择开始时间"
              format="YYYY年MM月DD日 HH时"
              style="width: 100%"
              @change="handleEndTimeChange"
            />
          </el-form-item>
        </el-col>
        <span>工时（天和小时）&emsp;</span>
        <el-form-item prop="leaveHoursDisplay">
          <el-input v-model="ruleForm.leaveHoursDisplay" disabled />
        </el-form-item>
      </el-form-item>
      <el-form-item label="总工时">
        <el-input v-model="ruleForm.leaveHours" style="width: 50px" />
        <span>（小时）</span>
      </el-form-item>
      <el-form-item label="报到时间">
        <el-date-picker
          v-model="ruleForm.reportTime"
          aria-label="请选择报到时间"
          type="datetime"
          placeholder="请选择报到时间"
          format="YYYY年MM月DD日 hh时"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="请假事由" prop="leaveReason">
        <el-input
          v-model="ruleForm.leaveReason"
          type="textarea"
          placeholder="请输入请假原因(最多140字)"
          show-word-limit
          maxlength="140"
        />
      </el-form-item>
      <el-form-item label="部门领导" prop="leaderName">
        <el-input v-model="ruleForm.leaderName" disabled />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          修改
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import { useCounterStore } from "@/stores/counter";
import { ElMessage, ElMessageBox } from "element-plus";
const store = useCounterStore();
const router = useRouter();
const route = useRoute();
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
const cities = ["事假", "病假", "婚假", "产假", "丧假", "年假", "调休", "其他"];
interface RuleForm {
  laId: number;
  leaveId: number;
  leaveName: string;
  departmentId: number;
  leaveType: string;
  startTime: string;
  endTime: string;
  leaveHours: number;
  reportTime: string;
  leaveReason: string;
  leaderName: string;
  leaderIds: string;
  statusId: number;
  statusName: string;
  createTime: string;
  isDeleted: false;
  powerId: number;
  leaveHoursDisplay: string;
}

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  laId: 0,
  leaveId: 0,
  leaveName: "",
  departmentId: 0,
  leaveType: "事假",
  startTime: "",
  endTime: "",
  leaveHours: 0,
  reportTime: "",
  leaveReason: "",
  leaderName: "",
  leaderIds: "",
  statusId: 0,
  statusName: "",
  createTime: "2025-03-05T10:49:14.644Z",
  isDeleted: false,
  powerId: 0,
  leaveHoursDisplay: "",
});

const locationOptions = ["Home", "Company", "School"];

const rules = reactive<FormRules<RuleForm>>({
  leaveReason: [
    { required: true, message: "请输入原因", trigger: "blur" },
    { min: 1, max: 140, message: "长度最多140字", trigger: "blur" },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios({
        url: "https://localhost:7070/api/Leva/UpdLeave",
        method: "post",
        data: ruleForm,
      }).then((res) => {
        if (res.data.code == 300) {
          ElMessage.success(res.data.message);
          router.push("/GetLeave");
        } else {
          ElMessage.error(res.data.message);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));

//请假申请反填
const getLeave = () => {
  axios({
    url: "https://localhost:7070/api/LevaApp /GetLAId",
    method: "get",
    params: {
      LAId: route.query.id,
    },
  }).then((res) => {
    if (res.data.code == 600) {
      ruleForm.laId = res.data.data.laId;
      ruleForm.leaveId = res.data.data.leaveId;
      ruleForm.leaveName = res.data.data.leaveName;
      ruleForm.departmentId = res.data.data.departmentId;
      ruleForm.leaveType = res.data.data.leaveType;
      ruleForm.startTime = res.data.data.startTime;
      ruleForm.endTime = res.data.data.endTime;
      ruleForm.leaveHours = res.data.data.leaveHours;
      ruleForm.reportTime = res.data.data.reportTime;
      ruleForm.leaveReason = res.data.data.leaveReason;
      ruleForm.leaderName = res.data.data.leaderName;
      ruleForm.leaderIds = res.data.data.leaderIds;
      ruleForm.statusId = res.data.data.statusId;
      ruleForm.statusName = res.data.data.statusName;
      ruleForm.createTime = res.data.data.createTime;
      ruleForm.isDeleted = res.data.data.isDeleted;
    }
  });
};
// 处理开始时间改变
const handleStartTimeChange = () => {
  if (ruleForm.startTime && ruleForm.leaveHours) {
    const startTime = new Date(ruleForm.startTime);
    const endTime = new Date(
      startTime.getTime() + ruleForm.leaveHours * 60 * 60 * 1000
    );
    ruleForm.endTime = endTime.toISOString().slice(0, 16).replace("T", " ");
  }
  calculateLeaveHours();
};

// 处理结束时间改变
const handleEndTimeChange = () => {
  calculateLeaveHours();
};

// 处理请假工时改变
const handleLeaveHoursChange = () => {
  if (ruleForm.startTime && ruleForm.leaveHours) {
    const startTime = new Date(ruleForm.startTime);
    const endTime = new Date(
      startTime.getTime() + ruleForm.leaveHours * 60 * 60 * 1000
    );
    ruleForm.endTime = endTime.toISOString().slice(0, 16).replace("T", " ");
  }
  calculateLeaveHours();
};

// 处理报到时间改变
const handleReportTimeChange = () => {
  // 可以在这里添加更多报到时间相关的逻辑
};

// 处理报到时间改变
const calculateLeaveHours = () => {
  const startTime = new Date(ruleForm.startTime);
  const endTime = new Date(ruleForm.endTime);

  const startDay = startTime.getDate();
  const sh = startTime.getHours();
  const endDay = endTime.getDate();
  const eh = endTime.getHours();

  const startHour = sh < 9 ? 9 : sh > 18 ? 18 : sh;
  const endHour = eh < 9 ? 9 : eh > 18 ? 18 : eh;

  if (ruleForm.leaveHours !== undefined && ruleForm.leaveHours !== null) {
    let days = 0;
    let hours = 0;

    // 完整天计算
    if (startDay < endDay) {
      days = endDay - startDay - 1;

      // 开始天计算
      hours = 18 - startHour - (startHour < 13 ? 1 : 0);

      // 结尾天计算
      hours += endHour - 9 - (endHour > 12 ? 1 : 0);

      // 特殊情况：开头结尾都是满的
      hours === 16 ? ((hours = 0), (days += 2)) : 0;

      // 工时满8进一
      hours >= 8 ? ((hours -= 8), (days += 1)) : 0;
    }
    //开头结尾同天计算
    else if (startDay === endDay) {
      hours = endHour - startHour - (endHour >= 13 && startHour <= 12 ? 1 : 0);
    }

    // 格式化显示工时
    ruleForm.leaveHoursDisplay = `${days}天${hours}小时`;
    ruleForm.leaveHours = 8 * days + hours;
  } else {
    ruleForm.leaveHours = 0;
    ruleForm.leaveHoursDisplay = "";
  }
};
onMounted(() => {
  getLeave();
});
</script>

<style scoped>
</style>